package com.boyi.center.controller.impl;

import com.boyi.shared.common.R;
import com.boyi.shared.common.Result;
import com.boyi.shared.qrcode.QRCode;
import com.boyi.shared.qrcode.QRCodeFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * 处理登录请求
 */
@RestController
@Api(value = "登录模块接口->api", tags = {"API登录Controller"})
public class LoginController {
    @ApiOperation("登录")
    @PostMapping("login")
    public Result login(String checkCode, HttpServletRequest request) {
        String code = request.getParameter("checkCode");
        HttpSession session = request.getSession();
        if (!code.equalsIgnoreCase((String) session.getAttribute("randCheckCode"))) {
            request.setAttribute("errorMsg", "验证码不正确");
            return R.error("验证码不正确");
        }
        return R.ok();
    }

    @ApiOperation("获取验证码")
    @GetMapping("pictureCheckCode")
    public void pictureCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 设置不缓存图片
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);

        // 指定生成的响应图片,一定不能缺少这句话,否则错误.
        response.setContentType("image/jpeg");
        QRCode qrCode = QRCodeFactory.generate(80, 35);
        HttpSession session = request.getSession(true);
        session.setAttribute("randCheckCode", qrCode.getContent());
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(qrCode.getImage(), "JPEG", response.getOutputStream());// 输出图片
        outputStream.flush();
        outputStream.close();
    }

}
